import datetime

from api.extension import return_code
from api.models import UserInfo
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed


# 认证校验，认证成功后才能访问
class TokenAuthentication(BaseAuthentication):
    def authenticate(self, request):
        token = request.query_params.get('token')
        if not token:
            raise AuthenticationFailed({'code': return_code.AUTH_FAILED, 'error': '认证失败'})

        user_obj = UserInfo.objects.filter(token=token).first()
        if not user_obj:
            raise AuthenticationFailed({'code': return_code.AUTH_FAILED, 'error': '认证失败'})

        if datetime.datetime.now() > user_obj.token_expiry_date:
            raise AuthenticationFailed({'code': return_code.AUTH_OVERDUE, 'error': '认证过期'})

        return user_obj, token

    def authenticate_header(self, request):
        return 'Bearer realm=API'


# 登录，不登录，均可访问。登录显示用户对文章的推荐和收藏状态
class UserAnonTokenAuthentication(BaseAuthentication):
    def authenticate(self, request):
        token = request.query_params.get('token')
        if not token:
            return None
        user_obj = UserInfo.objects.filter(token=token).first()
        if not user_obj:
            return None
        if datetime.datetime.now() > user_obj.token_expiry_date:
            return None

        return user_obj, token

    def authenticate_header(self, request):
        return 'Bearer realm=API'
